package com.example.homeworkhelper.userInfo.setting;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.example.homeworkhelper.R;
import com.example.homeworkhelper.userInfo.UserDto;
import com.example.homeworkhelper.userInfo.UserInfoActivity;
import com.example.homeworkhelper.utils.common.Config;
import com.google.android.material.textfield.TextInputEditText;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.Map;

import javax.sql.StatementEvent;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class SettingActivity extends AppCompatActivity implements View.OnClickListener {
    // setting main
    private Button btnOpenAve;
    private Button btnOpenName;
    private Button btnOpenIdentity;
    private TextView tvName;
    private TextView tvId; // id for identity
    // setting -> change name
    private View layoutName; // 装name组件的容器
    private View iconName;
    private TextInputEditText tiName;
    private Button btnConfirmName;
    // setting -> select identity
    private View imgGoBack;
    private View settingMain;
    private View select2;
    private View select1;
    private View iAmStu;
    private View iAmPar;
    private View iAmTea;

    private RadioGroup radioGroup;
    private Button btnConfirmSelect;

    UserDto userDto;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);

        userDto = readCacheDto();
        initSettingMain();
        initNameChange();
        initSelectId();
        refreshSettingMainText();
    }

    private void initNameChange() {

        iconName = findViewById(R.id.img_name_icon);
        layoutName = findViewById(R.id.layout_setting_name);
        tiName = findViewById(R.id.ti_name);
        btnConfirmName = findViewById(R.id.btn_confirm_name);

        btnConfirmName.setOnClickListener(this);
    }

    private void initSettingMain() {

        btnOpenAve = findViewById(R.id.btn_open_ave);
        btnOpenName = findViewById(R.id.btn_open_name);
        btnOpenIdentity = findViewById(R.id.btn_open_identity);

        btnOpenAve.setOnClickListener(this);
        btnOpenIdentity.setOnClickListener(this);
        btnOpenName.setOnClickListener(this);

        tvName = findViewById(R.id.text_setting_name);
        tvId = findViewById(R.id.text_setting_role);

    }

    private void initSelectId() {


        select1 = findViewById(R.id.select1);
        select2 = findViewById(R.id.select2);

        imgGoBack = findViewById(R.id.go_back);
        iAmPar = findViewById(R.id.i_am_parent);
        iAmStu = findViewById(R.id.i_am_student);
        iAmTea = findViewById(R.id.i_am_teacher);
        btnConfirmSelect = findViewById(R.id.btn_confirm_select_id);

        radioGroup = (RadioGroup) findViewById(R.id.radioGroup_select_grade);

        imgGoBack.setOnClickListener(this);
        iAmTea.setOnClickListener(this);
        iAmPar.setOnClickListener(this);
        iAmStu.setOnClickListener(this);
        btnConfirmSelect.setOnClickListener(this);


    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_open_ave:
                // TODO: 头像
                return;
            case R.id.btn_open_name:
                if (layoutName.getVisibility() == View.VISIBLE) {
                    iconName.setRotation(0);
                    layoutName.setVisibility(View.GONE);
                } else {
                    iconName.setRotation(90);
                    layoutName.setVisibility(View.VISIBLE);
                }
                return;
            case R.id.btn_open_identity:
                settingMain = findViewById(R.id.setting_main);
                settingMain.setVisibility(View.GONE);
                imgGoBack.setVisibility(View.VISIBLE);
                select1.setVisibility(View.VISIBLE);
                select2.setVisibility(View.VISIBLE);
                return;
        }

        switch (view.getId()) {
            case R.id.go_back:
                settingMain.setVisibility(View.VISIBLE);
                imgGoBack.setVisibility(View.GONE);
                select1.setVisibility(View.GONE);
                select2.setVisibility(View.GONE);
                break;
            case R.id.i_am_parent:
                iAmPar.setBackground(getDrawable(R.drawable.background));
                iAmStu.setBackground(null);
                iAmTea.setBackground(null);
                userDto.setRole_id(1);
                userDto.setRole_name("家长");
                break;
            case R.id.i_am_student:
                iAmPar.setBackground(null);
                iAmStu.setBackground(getDrawable(R.drawable.background));
                iAmTea.setBackground(null);
                userDto.setRole_id(2);
                userDto.setRole_name("学生");
                break;
            case R.id.i_am_teacher:
                iAmPar.setBackground(null);
                iAmStu.setBackground(null);
                iAmTea.setBackground(getDrawable(R.drawable.background));
                userDto.setRole_id(0);
                userDto.setRole_name("老师");
                break;
        }

        switch (view.getId()) {

            case R.id.btn_confirm_name:
                userDto.setU_name(tiName.getText().toString());
                if (userDto.getU_name().length() > 8) {
                    Toast.makeText(this, "昵称最长为8位", Toast.LENGTH_LONG).show();
                    return;
                }

                postModName(userDto.getU_name());

                writeCacheDto(userDto);
                this.finish();
                break;

            case R.id.btn_confirm_select_id:
                int id = radioGroup.getCheckedRadioButtonId();
                switch (id) {
                    case R.id.x1:
                        userDto.setGrade("小学一年级");
                        break;
                    case R.id.x2:
                        userDto.setGrade("小学二年级");
                        break;
                    case R.id.x3:
                        userDto.setGrade("小学三年级");
                        break;
                    case R.id.x4:
                        userDto.setGrade("小学四年级");
                        break;
                    case R.id.x5:
                        userDto.setGrade("小学五年级");
                        break;
                    case R.id.x6:
                        userDto.setGrade("小学六年级");
                        break;
                    case R.id.c1:
                        userDto.setGrade("初中一年级");
                        break;
                    case R.id.c2:
                        userDto.setGrade("初中二年级");
                        break;
                    case R.id.c3:
                        userDto.setGrade("初中三年级");
                        break;
                    case R.id.g1:
                        userDto.setGrade("高中一年级");
                        break;
                    case R.id.g2:
                        userDto.setGrade("高中二年级");
                        break;
                    case R.id.g3:
                        userDto.setGrade("高中三年级");
                        break;
                    case R.id.d1:
                        userDto.setGrade("大学一年级");
                        break;
                    case R.id.d2:
                        userDto.setGrade("大学二年级");
                        break;
                    case R.id.d3:
                        userDto.setGrade("大学三年级");
                        break;
                    case R.id.d4:
                        userDto.setGrade("大学四年级");
                        break;
                    default:
                        Toast.makeText(this, "请选择年级", Toast.LENGTH_LONG).show();
                        return;
                }

                postModRole(userDto.getRole_id(), userDto.getGrade());

                writeCacheDto(userDto);
                this.finish();
                break;
        }
    }

    private UserDto readCacheDto() {
        UserDto dto;
        SharedPreferences sharedPreferences = getSharedPreferences("userInfor", Context.MODE_PRIVATE);
        if ( sharedPreferences.getBoolean("isLogin", false)) {
            Map userJson = sharedPreferences.getAll();
            Gson gson = new Gson();
            String nJson = gson.toJson(userJson);
            dto = gson.fromJson(nJson, UserDto.class);
        } else {
            dto = new UserDto();
            dto.setU_id("-1");
            writeCacheDto(dto);
        }
        return dto;

    }

    private void writeCacheDto(@NonNull UserDto userDto) {
        SharedPreferences sharedPreferences = getSharedPreferences("userInfor", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("u_name", userDto.getU_name());
        editor.putString("u_avatar", userDto.getU_avatar());
        editor.putString("gender", userDto.getGender());
        editor.putString("role_name", userDto.getRole_name());
        editor.putString("phone", userDto.getPhone());
        editor.putString("grade", userDto.getGrade());
        editor.putString("u_id", userDto.getU_id());
        editor.putInt("role_id", userDto.getRole_id());
        editor.commit();
    }

    private void refreshSettingMainText() {
        UserDto userDto = readCacheDto();
        tvName.setText(userDto.getU_name());
        switch (userDto.getRole_id()) {
            case 0:
                userDto.setRole_name("教师");
                break;
            case 1:
                userDto.setRole_name("家长");
                break;
            case 2:
                userDto.setRole_name("学生");
                break;
        }
        String roleString = userDto.getGrade() == null ? "未选择角色" : userDto.getRole_name() + " / " + userDto.getGrade();
        tvId.setText(roleString);
    }


    private void postModRole(int role_id, String grade) {
        String url = Config.HttpUrlHead + "/user_info/mod/role";
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()    //构建body
                .add("u_id", userDto.getU_id())
                .add("role_id", String.valueOf(role_id))
                .add("grade", grade)
                .build();

        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    okHttpClient.newCall(request).execute();
                    ;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        t.start();
        try {
            t.join();
        } catch (Exception e) {
            e.printStackTrace();
        }
        refreshSettingMainText();
    }


    private void postModName(String u_name) {
        String url = Config.HttpUrlHead + "/user_info/mod/name";
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()    //构建body
                .add("u_id", userDto.getU_id())
                .add("u_name", u_name)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    okHttpClient.newCall(request).execute();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        t.start();
        try {
            t.join();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}